package com.yxjx.duoxue.audition;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.Constants;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.activities.ActivityIntroductionActivity;
import com.yxjx.duoxue.customview.YxRadioGroup;
import com.yxjx.duoxue.datamodel.DMObject;
import com.yxjx.duoxue.datamodel.DMReg;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.payment.ClientUserKidsDTS;
import com.yxjx.duoxue.payment.OrderKidsConfigurationView;
import com.yxjx.duoxue.payment.OrderSubmitActivity;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class ApointmentAuditionActivity extends BaseActionBarActivity {
	
	public static final int SEX_MAN = 1;
	public static final int SEX_WOMAN = 2;
	
	public static final String EXTRA_FIELD_1 = "EXTRA_FIELD_1";
	public static final String EXTRA_FIELD_2 = "EXTRA_FIELD_2";
	public static final String EXTRA_FIELD_3 = "EXTRA_FIELD_3";
	private static final int REQ_CODE_FINISH_PAGE = 0;
	private OrderKidsConfigurationView kidInfoView;
	private Context mContext;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_apointment_free_audition);
		customizeActionBarTitle(R.string.free_audition_title);
		mContext = this;

		//  记录预约信息
		mRegInfo = new DMReg();
		
		Bundle extra = getIntent().getExtras();
		if (extra != null) {
			// 预约内容，课程or活动
			mBookType = extra.getInt(Yx.KEY_BOOK_TYPE);
			// 预约课程or活动的id
			mBookItemId = Long.valueOf(extra.getString(Yx.KEY_BOOK_ITEM_ID));
			
			mRegInfo.setBookType(mBookType);
			mRegInfo.setBookItemName(extra.getString(Yx.KEY_BOOK_ITEM_NAME));
			mRegInfo.setSchoolName(extra.getString(Yx.KEY_BOOK_SCHOOL_NAME));
		}
		
		if (mBookType == Yx.TYPE_ITEM_ACTIVITY) {
			customizeActionBarTitle("报名活动");
		} else if (mBookType == Yx.TYPE_ITEM_COURSE) {
			customizeActionBarTitle(R.string.free_audition_title);
		}
		
		UIHelper.setText(findViewById(R.id.scroll), R.id.course_name, mRegInfo.getBookItemName());
		
		View root = findViewById(R.id.scroll_root);
		UIHelper.setClickListener(root, R.id.submit, mClickListener);
		UIHelper.setClickListener(root, R.id.root, mClickListener);
		
		kidInfoView = (OrderKidsConfigurationView) findViewById(R.id.kid_info);
		mChildName = (EditText) kidInfoView.findViewById(R.id.child_name);
		mChildSex = (YxRadioGroup) findViewById(R.id.child_sex);
		mChildBirth = (TextView) kidInfoView.findViewById(R.id.child_birth);
		
		mParentName = (EditText) findViewById(R.id.parent_name);
		mParentSex = (YxRadioGroup) findViewById(R.id.parent_sex);
		mParentSex.customizeLabels();
		mParentPhone = (EditText) findViewById(R.id.parent_phone);
		
		final View submit = root.findViewById(R.id.submit);
		mParentPhone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				hideIME(submit);
				mClickListener.onClick(submit);
				return false;
			}
		});
		
		mULrsp = UserLoginResponse.getInstance(getApplicationContext());
		if (mULrsp == null) {
			// 重新登录。
			return;
		}
		
		mParentPhone.setText(mULrsp.getPhoneNumber());
		
		tryToFillKidInfo();

	}
	
	private void tryToFillKidInfo() {
		kidInfoView.updateByLoginInfo();
		// scroll置顶。
		UIHelper.resetScroll(this, R.id.scroll);
		UIHelper.requestFocus(kidInfoView, R.id.child_name);
	}

	private void customizeSharePageContent() {
		
		String part1Str = "";
		String part2Str = "";
		
		if (mBookType == Yx.TYPE_ITEM_ACTIVITY) {
			part1Str = getResources().getString(R.string.activity_apoint_done_para1);
			part2Str = getResources().getString(R.string.activity_apoint_done_para2);
		} else {
			part1Str = getResources().getString(R.string.course_apoint_done_para1);
			part2Str = getResources().getString(R.string.course_apoint_done_para2);
		}
		
		part1Str = part1Str.replace("#child_name", mRegInfo.getChildName())
				.replace("#child_sex", mRegInfo.getChildSex() == 1 ? "男" : "女")
				.replace("#child_age", "" + mRegInfo.getChildAge())
				.replace("#school_name", "" + mRegInfo.getSchoolName())
				.replace("#course_name", "" + mRegInfo.getBookItemName());
		part2Str = part2Str.replace("#school_name", "" + mRegInfo.getSchoolName());
		
		Intent intent = getIntent();
		intent.setClass(getApplicationContext(), ApointmentDoneActivity.class);
		intent.putExtra(EXTRA_FIELD_1, part1Str);
		intent.putExtra(EXTRA_FIELD_2, part2Str);
		startActivityForResult(intent, REQ_CODE_FINISH_PAGE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQ_CODE_FINISH_PAGE) {
			if (resultCode == RESULT_OK) {
				finish();
			}
		}
	}

	private View.OnClickListener mClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.share_button:
				break;
			case R.id.submit:
				if (mBookType == Yx.TYPE_ITEM_ACTIVITY) {
					StatHelper.addKVEvent(mContext, "event_activity_reg_submit",
							StatHelper.KEY_ACTIVITY, mBookItemId);
				}
				submitAppointItem(arg0);
				break;
			case R.id.root:
				hideIME(arg0);
				break;
			default:
				break;
			}
		}
	};
	
	class BookItemAsyncTask extends AsyncTask<String, Integer, ResponseObject> {

		@Override
		protected ResponseObject doInBackground(String... arg0) {
			
			int ret = 0;
			String jsonString = arg0[0];
			JSONObject params;
			// 封装参数
			try {
				params = new JSONObject(jsonString);
			} catch (JSONException e) {
				// 参数错误
				e.printStackTrace();
				ret = -1;
				return new ResponseObject(-1, "");
			}
			
			// book info. 
			try {
				// 隐藏IME
				hideIME(mChildName);
				ResponseObject code = UserReg.requestBookItem(mULrsp, mBookType, params, ApointmentAuditionActivity.this);
				return code;
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return new ResponseObject(-1, "");
		}
		
		@Override
		protected void onPostExecute(ResponseObject result) {
			super.onPostExecute(result);
			if (result.getCode() == MsgCode.SUCCESS) {
				Toast.makeText(getApplicationContext(), "预约成功", Toast.LENGTH_SHORT).show();
				setResult(RESULT_OK);
				customizeSharePageContent();
				// 标记为已经访问过课程或活动
				Utils.writeToSharePreference(ApointmentAuditionActivity.this, Yx.KEY_HAS_APPOINT_OR_BUY_OR_COMMENT, "1");
				
			} else {
				Toast.makeText(getApplicationContext(), "预约失败, " + MsgCode.descFor(result), Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private void submitAppointItem(View arg0) {
		String childName = "";
		int childSex = 0;
		int childBirthYear = -1;
		int childBirthMonth = -1;
		String parentName = "";
		int parentSex = 0;
		String parentPhone = "";
		
		childName = mChildName.getText().toString();
		if (UIHelper.isEmpty(childName)) {
			UIHelper.showTips(arg0, "学生姓名不能为空");
			return;
		}
		
		childSex = mChildSex.getSelectedIndex();
		if (childSex != 1 && childSex != 2){
			UIHelper.showTips(arg0, "请选择学生性别");
			return;
		}
		
		childBirthYear = kidInfoView.getSelectedYear();
		childBirthMonth = kidInfoView.getSelectedMonth();
		
		if (!kidInfoView.isValidBirthDay()) {
			UIHelper.showTips(arg0, "请选择学生出生年月");
			return;
		}
		
		parentName = mParentName.getText().toString();
		if (UIHelper.isEmpty(parentName)) {
			UIHelper.showTips(arg0, "联系人姓名不能为空");
			return;
		}
		
		parentSex = mParentSex.getSelectedIndex();
		if (parentSex != SEX_WOMAN && parentSex != SEX_MAN) {
			UIHelper.showTips(arg0, "请选择联系人性别");
			return;
		}
		
		parentPhone = mParentPhone.getText().toString();
		if (!Utils.isMobileNumber(parentPhone)) {
			UIHelper.showTips(arg0, "请输入联系人手机号码");
			return;
		}
		
		// request to book the activity/course.
		JSONObject info = new JSONObject();
		try {
			info.put("id", "" + mBookItemId); // activity/course id
			info.put("name", childName);
			info.put("sex", "" + childSex);
			info.put("studentBirthYear", "" + childBirthYear);
			info.put("studentBirthMonth", "" + childBirthMonth);
			
			info.put("contactName", parentName);
			info.put("contactSex", "" + parentSex);
			info.put("mobile", parentPhone);

			mRegInfo.setBookItemId(mBookItemId);
			mRegInfo.setChildAge(Utils.getOlderYear(childBirthYear,
					childBirthMonth));
			mRegInfo.setChildName(childName);
			mRegInfo.setChildSex(childSex);

			mRegInfo.setParentName(parentName);
			mRegInfo.setParentPhone(parentPhone);
			mRegInfo.setParentSex(parentSex);
			
		} catch (JSONException e) {
			e.printStackTrace();
			UIHelper.showTips(arg0, "预约试听发送数据格式错误");
			return;
		} 
		
		BookItemAsyncTask bookTask = new BookItemAsyncTask();
		bookTask.execute(info.toString());
	}

	private EditText mChildName;
	private YxRadioGroup mChildSex;
	private TextView mChildBirth;
	private EditText mParentName;
	private YxRadioGroup mParentSex;
	private EditText mParentPhone;
	private UserLoginResponse mULrsp;
	private int mBookType = -1;
	private long mBookItemId = 0;
	private DMReg mRegInfo;
	
}
